<template>
  <div class="search-suggestion">
    <van-cell icon="search" v-for="item in suggestions.options" :key="item.id" @click="$emit('search',item)">
      <template #title>
        <div v-html="highlight(item)"></div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { reactive, watch } from '@vue/runtime-core'
import { Toast } from 'vant'
import { getSearchSuggestions } from '@/api/search'
import { debounce, compact } from 'lodash'

export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  setup (props) {
    const suggestions = reactive({ options: [] })
    async function loadSearchSuggestions (q) {
      try {
        const { data } = await getSearchSuggestions(q)
        suggestions.options = compact(data.data.options)// 去除假值
      } catch (err) {
        Toast('获取失败')
      }
    }
    // 搜索字高亮
    function highlight (text) {
      const reg = new RegExp(props.searchText, 'gi')// 在正则表达式中放入变量
      return text.replace(reg, `<span class="active">${props.searchText}</span>`)// replace不修改原始数据
    }
    // 搜索框内容变动触发
    watch(() => props.searchText, debounce((newValue) => { // 防抖，内容变动一段时间后结算
      loadSearchSuggestions(newValue)
    }, 200), { immediate: true })// 组件出现时直接触发一次

    return {
      suggestions,
      highlight
    }
  }
}
</script>

<style lang='less' scoped>
.search-suggestion{
  /deep/span.active{
    color:#3296fa
  }
}
</style>
